<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">

      <a-form-item class="smart-query-form-item" label="订单编号">
        <a-input v-model:value="queryForm.orderKey" placeholder="请输入订单编号" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="邮寄单号">
        <a-input v-model:value="queryForm.expno" placeholder="请输入邮寄单号" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="寄件人">
        <a-input v-model:value="queryForm.lnker" placeholder="请输入寄件人" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="机器编码">
        <a-input v-model:value="queryForm.machineCode" placeholder="请输入机器编码" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="收款账户">
        <a-input v-model:value="queryForm.payacc" placeholder="请输入收款账户" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="收款人">
        <a-input v-model:value="queryForm.payname" placeholder="请输入收款人" style="width: 160px"/>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="订单状态">
        <a-select v-model:value="queryForm.ostat" allowClear placeholder="选择订单状态" style="width: 160px">
          <a-select-option :value="10">待上门取件</a-select-option>
          <a-select-option :value="11">物流运输中</a-select-option>
          <a-select-option :value="12">到货待质检</a-select-option>
          <a-select-option :value="13">质检中</a-select-option>
          <a-select-option :value="20">揽件前取消</a-select-option>
          <a-select-option :value="21">待退回</a-select-option>
          <a-select-option :value="22">已退回</a-select-option>
          <a-select-option :value="30">待确认交易</a-select-option>
          <a-select-option :value="31">待打款</a-select-option>
          <a-select-option :value="32">打款失败</a-select-option>
          <a-select-option :value="33">交易完成</a-select-option>
          <a-select-option :value="88">异常关闭</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="下单时间">
        <a-space :size="12" direction="vertical">
          <a-range-picker v-model:value="otime" :ranges="defaultTimeRanges" @change="otimeChange"/>
        </a-space>
      </a-form-item>
      <a-form-item class="smart-query-form-item" label="打款时间">
        <a-space :size="12" direction="vertical">
          <a-range-picker v-model:value="otime33" :ranges="defaultTimeRanges" @change="otime33Change"/>
        </a-space>
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button type="primary" @click="resetPageNumAjaxQuery">
          <template #icon>
            <SearchOutlined/>
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery">
          <template #icon>
            <ReloadOutlined/>
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card :bordered="false" :hoverable="true" size="small">
    <div style="margin-bottom: 8px">
      <a-button size="small" style="margin-right: 8px" type="primary" @click="orderExport">导出</a-button>
      <a-button size="small" style="margin-right: 8px" type="danger" @click="showPayErrorModal">打款失败</a-button>
      <a-button size="small" type="primary" @click="showPaySuccessModal">打款成功</a-button>
    </div>
    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="tableLoading"
        :locale="{emptyText: '暂无数据'}"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: rowSelectionChange }"
        :scroll="{ x: 2300 }"
        bordered
        rowKey="id"
        size="small"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'ostat'">
          {{ STATUS[text] }}
        </template>
        <template v-if="column.dataIndex === 'oriModelName'">
          <span v-if="record.orderWay===1">{{ text }}</span>
          <span v-else>手机 X{{ record.phoneNum || 0 }} 平板 X{{ record.padNum || 0 }}</span>
        </template>
        <template v-if="column.dataIndex === 'mrp'">
          {{ record.orderWay === 1 ? text : '-' }}
        </template>
        <template v-if="column.dataIndex === 'machineCodes'">
          <div v-for="d in text">
            {{ d }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'brps'">
          <div v-for="d in text">
            {{ d }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'checkResultFlag'">
          {{ QUALITYSTATUSALL[text] }}
        </template>
        <template v-if="column.dataIndex === 'orderWay'">
          {{ text == 1 ? '估价下单' : '批量下单' }}
        </template>
        <template v-if="column.dataIndex === 'accountType'">
          <span>支付宝账号</span>
        </template>

        <template v-if="column.dataIndex === 'operate'">
          <div class="smart-table-operate">
            <a-button type="link" @click="toDetail(record)">查看详情</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
          v-model:current="queryForm.pageNum"
          v-model:pageSize="queryForm.pageSize"
          :defaultPageSize="queryForm.pageSize"
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :show-total="(total) => `共${total}条`"
          :total="total"
          show-less-items
          showQuickJumper
          showSizeChanger
          @change="ajaxQuery"
          @showSizeChange="ajaxQuery"
      />
    </div>
  </a-card>
  <printer ref="printerRef"></printer>

  <!--  打款成功对话框-->
  <a-modal :visible="paySuccessModal.visible" title="打款成功" width="500px" @cancel="hidePaySuccessModal"
           @ok="submitPaySuccess">
    请确认勾选的订单已成功打款，确认后订单状态变为打款成功
  </a-modal>
  <!--  打款失败对话框-->
  <a-modal :visible="payErrorModal.visible" title="打款失败" width="500px" @cancel="hidePayErrorModal" okType="danger"
           @ok="submitPayError">
    <div>是否将勾选的订单标记为打款失败？</div>
    <div>失败原因：
      <a-select v-model:value="payErrorModal.type" allowClear placeholder="选择失败原因" style="width: 200px">
        <a-select-option :value="1">收款信息为空</a-select-option>
        <a-select-option :value="2">收款信息有误或未实名</a-select-option>
      </a-select>
    </div>
  </a-modal>


</template>


<script setup>
import {PAGE_SIZE, PAGE_SIZE_OPTIONS} from "/@/constants/common-const";
import {nextTick, onMounted, reactive, ref} from "vue";
import {smartSentry} from "/@/lib/smart-sentry";
import {message, Modal} from "ant-design-vue";
import {SmartLoading} from '/@/components/framework/smart-loading';
import {defaultTimeRanges} from "/@/lib/default-time-ranges";

import {useRoute, useRouter} from 'vue-router';
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import _ from "lodash";
import {orderApi, QUALITYSTATUSALL, STATUS as ORDERSTATUS, STATUS} from "/@/views/business/order/order";
import {inventoryApi} from "/@/views/business/storage/inventory";
import Printer from "/@/views/business/printer/printer.vue";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {recoveryApi} from "/@/views/business/finance-center/recovery-order";


const printerRef = ref();
const router = useRouter();
const route = useRoute();

const columns = ref([
  {
    align: 'center',
    title: '订单编号',
    dataIndex: 'orderKey',
    width: 120,
  },
  {
    align: 'center',
    title: '下单时间',
    dataIndex: 'otime',
    width: 120,
  },
  {
    align: 'center',
    title: '订单状态',
    dataIndex: 'ostat',
    width: 80,
  },
  {
    align: 'center',
    title: '快递单号',
    dataIndex: 'expno',
    width: 120,
  },
  {
    align: 'center',
    title: '寄件人姓名',
    dataIndex: 'lnker',
    width: 80,
  },
  {
    align: 'center',
    title: '寄件人手机号',
    dataIndex: 'lnktel',
    width: 80,
  },
  {
    align: 'center',
    title: '下单型号',
    dataIndex: 'oriModelName',
    width: 180,
  },
  {
    align: 'center',
    title: '预估回收价',
    dataIndex: 'mrp',
    width: 80,
  },
  {
    align: 'center',
    title: '机器编码',
    dataIndex: 'machineCodes',
    width: 180,
  },
  {
    align: 'center',
    title: '质检价格',
    dataIndex: 'brps',
    width: 80,
  },
  {
    align: 'center',
    title: '实际回收价',
    dataIndex: 'trp',
    width: 80,
  },
  {
    align: 'center',
    title: '账户类型',
    dataIndex: 'accountType',
    width: 120,
  },
  {
    align: 'center',
    title: '质检结果',
    dataIndex: 'checkResultFlag',
    width: 120,
  },
  {
    align: 'center',
    title: '打款时间',
    dataIndex: 'otime33',
    width: 120,
  },
  {
    align: 'center',
    title: '下单方式',
    dataIndex: 'orderWay',
    width: 80,
  },
  {
    align: 'center',
    title: '操作',
    dataIndex: 'operate',
    width: 160,
    fixed: 'right'
  },
]);

const queryFormDataDefault = {
  orderKey: undefined,
  expno: undefined,
  lnker: undefined,
  machineCode: undefined,
  payacc: undefined,
  payname: undefined,
  ostat: undefined,
  otimeBegin: undefined,
  otimeEnd: undefined,
  otime33Begin: undefined,
  otime33End: undefined,
  pageNum: 1,
  pageSize: PAGE_SIZE,
};
const queryForm = reactive({...queryFormDataDefault});
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref();

let otime = ref();//下单时间
let otime11 = ref();//揽件时间
let otime12 = ref();//签收时间
let otime33 = ref();//打款时间

let selectedRows = [];
const selectedRowKeys = ref([]);
const paySuccessModal = reactive({
  visible: false
})
const payErrorModal = reactive({
  visible: false,
  type: undefined
})


onMounted(async () => {
  ajaxQuery();
});


function otimeChange(dates, dateStrings) {
  queryForm.otimeBegin = dateStrings[0];
  queryForm.otimeEnd = dateStrings[1];
}

function otime11Change(dates, dateStrings) {
  queryForm.otime11Begin = dateStrings[0];
  queryForm.otime11End = dateStrings[1];
}

function otime12Change(dates, dateStrings) {
  queryForm.otime12Begin = dateStrings[0];
  queryForm.otime12End = dateStrings[1];
}

function otime33Change(dates, dateStrings) {
  queryForm.otime33Begin = dateStrings[0];
  queryForm.otime33End = dateStrings[1];
}

function toDetail(record) {
  router.push({path: '/order/order-detail', query: {id: record.id}});
  // `https://test-xin.bashouj.com/a-api/order/sf/temple?orderId=${record.id}&expno=${record.expno}`
  // printerRef.value.printExpressInfo(record);
}


// 重置查询条件
function resetQuery() {
  Object.assign(queryForm, queryFormDataDefault);
  otime.value = [];
  otime11.value = [];
  otime12.value = [];
  otime33.value = [];
  ajaxQuery();
}

function resetPageNumAjaxQuery(){
  queryForm.pageNum = 1;
  ajaxQuery();
}
// 查询
async function ajaxQuery() {
  selectedRows = [];
  selectedRowKeys.value = [];
  try {
    tableLoading.value = true;
    let responseModel = await recoveryApi.queryPage(queryForm);
    const list = responseModel.data.list.map(item => {
      return {
        ...item,
        machineCodes: item.machineCodes ? item.machineCodes.split(',') : [],
        brps: item.brps ? item.brps.split(',') : []
      }
    });
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

function rowSelectionChange(keyArray, selected) {
  console.log(`selectedRowKeys: ${keyArray}`, 'selectedRows: ', selected);
  selectedRowKeys.value = keyArray;
  selectedRows = selected;
}


// 删除
function confirmDelete(record) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + record.questionName + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      singleDelete(record);
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

async function singleDelete(brandData) {
  try {
    SmartLoading.show();
    await orderApi.delete(brandData.id);
    message.success('删除成功');
    ajaxQuery();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

function showPayErrorModal() {
  if (!selectedRows.length) {
    return message.warn('请选择要操作的数据');
  }
  payErrorModal.visible = true;
}

function showPaySuccessModal() {
  if (!selectedRows.length) {
    return message.warn('请选择要操作的数据');
  }
  paySuccessModal.visible = true;
}

function hidePaySuccessModal() {
  paySuccessModal.visible = false;
}

function hidePayErrorModal() {
  payErrorModal.visible = false;
  payErrorModal.type = undefined;
}

function submitPaySuccess() {
  recoveryApi.paySuccess(selectedRows.map(i => i.id).join(',')).then((res) => {
    message.success(res.data);
    hidePaySuccessModal();
    ajaxQuery();
  });
}

function submitPayError() {
  if (!payErrorModal.type) {
    return message.error('请选择打款失败原因');
  }
  recoveryApi.payError(selectedRows.map(i => i.id).join(','), payErrorModal.type).then((res) => {
    message.success(res.data);
    hidePayErrorModal();
    ajaxQuery();
  });
}

function orderExport() {
  recoveryApi.orderExport(queryForm)
}
</script>

<style lang="less" scoped>

</style>